package com.jd.platform.gobrs.client.dispatcher;

import com.jd.platform.gobrs.client.size.CacheSizeHolder;
import com.jd.platform.gobrs.client.size.ObjectSizeCalculator;
import com.jd.platform.gobrs.common.enums.CacheHandlerEnums;
import com.jd.platform.gobrs.common.model.CacheSupplier;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: gobrs
 * @ClassName GCacheH
 * @description:
 * @author: sizegang
 * @create: 2022-01-08 23:01
 * @Version 1.0
 **/
@Slf4j
public class GCache extends AbstractGCacheBuilder {



    @Override
    public Object getCache(String key) {
        return dispatch(CacheHandlerEnums.MANUAL_CACHE.getType()).getCache(key);
    }

    @Override
    public Object getCache(String key, CacheSupplier cacheSupplier) {
        Object cache = dispatch(CacheHandlerEnums.MANUAL_CACHE.getType()).getCache(key);
        if (cache != null) {
            return cache;
        }
        Object cacheResult = cacheSupplier.get();
        try {
            setCache(key, cacheResult);
        } catch (Exception exception) {
            log.error("setCacheAuto key error {} key{}", exception, key);
        }
        return cacheResult;
    }

    @Override
    public Object getCacheAuto(String key) {
        return dispatch(CacheHandlerEnums.AUTO_CACHE.getType()).getCache(key);
    }

    @Override
    public Object getCacheAuto(String key, CacheSupplier cacheSupplier) {
        Object cache = dispatch(CacheHandlerEnums.AUTO_CACHE.getType()).getCache(key);
        if (cache != null) {
            System.out.println("缓存数据");
            return new byte[10240];
        }
        Object cacheResult = cacheSupplier.get();
        try {
            setCacheAuto(key, cacheResult);
            CacheSizeHolder.cacheSize.put(key, ObjectSizeCalculator.getObjectSize(cacheResult));
        } catch (Exception exception) {
            log.error("setCacheAuto key error {} key{}", exception, key);
        }
        return cacheResult;
    }

    @Override
    public boolean setCache(String key, Object value) {
        return dispatch(CacheHandlerEnums.MANUAL_CACHE.getType()).setCache(key, value);
    }

    @Override
    public boolean setCacheAuto(String key, Object value) {
        return dispatch(CacheHandlerEnums.MANUAL_CACHE.getType()).setCache(key, value);
    }

    @Override
    public boolean isHotKey(String key) {
        return dispatch(CacheHandlerEnums.MANUAL_CACHE.getType()).isHotKey(key);
    }
}
